<template>
      <n-flex justify="center" align="center">
        <div class="form-login" style="--width: 250px; --radius: 6px; --padding: 25px;">
          <n-form
            ref="formRef"
            :label-width="80"
            :model="formValue"
            :rules="rules"
            label-placement="left"
          >
            <n-form-item path="username">
              <n-input v-model:value="formValue.username" round placeholder="输入账号" >
                <template #prefix>
                  <n-icon :component="PersonOutline" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item path="password">
              <n-input
                type="password"
                round
                show-password-on="click"
                v-model:value="formValue.password"
                :input-props="{ autocomplete: 'off' }"
                placeholder="输入密码" >
                <template #prefix>
                  <n-icon :component="BagOutline" />
                </template>
              </n-input>
            </n-form-item>
            <n-button type="primary" attr-type="submit" @click="handleValidateClick">
              登录
            </n-button>
          </n-form>
        </div>
      </n-flex>
</template>
<script lang="ts" setup>
  import { ref } from 'vue'
  import { useRouter } from 'vue-router'
  import { NFlex, NForm, NFormItem, NInput, NButton, NGrid, NGi, NIcon } from 'naive-ui'
  import { PersonOutline, BagOutline } from '@vicons/ionicons5'

  import { login } from '@/api/user'
  import { setToken } from '@/utils/auth'
  import Md5 from 'js-md5'

  const router = useRouter()
  // 表单
  const formRef = ref(null)
  // 验证规则
  const rules = {
    username: { required: true, message: '请输入姓名', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' }
  }
  // 表单数据
  const formValue = ref({
    username: undefined,
    password: undefined,
  })

  /** 登录 */
  const handleValidateClick = (e) => {
    e.preventDefault()
    formRef.value?.validate((errors) => {
      if (!errors) {
        login({
          username: formValue.value.username,
          password: Md5(formValue.value.password)
        }).then(res => {
          setToken(res.token)
          router.push('/home')
        })
      }
      else {
        return false
      }
    })
  }
</script>
<style lang="scss" scoped>
  .n-flex {
    width: 100%;
    height: 100vh;
    background: url(@/assets/bg.gif) no-repeat center center fixed;
    background-size: cover;
    .form-login {
      border-radius: var(--radius);
      background: #ffffffaa;
      width: var(--width);
      padding: var(--padding);
      .n-button {
        width: 80%;
        margin-top: 20px;
      }
    }
  }
</style>